// ===============================================
// map_util
//
// Create by will on 2021/8/3 21:29
// Copyright @lankaidriver.All rights reserved.
// ===============================================

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:url_launcher/url_launcher.dart';

import '../core_intl/core_kit_localizations.dart';
import '../logger.dart';
import '../toast.dart';

enum MapType {
  aMap,
  tencent,
  biadu,
  apple,
}

Future<T?> mapUtilShowChooseDialog<T>({
  required BuildContext context,
  required String longitude,
  required String latitude,
  bool inApp = false,
  bool isShowTips = false,
  VoidCallback? onAppTap,
  VoidCallback? onTap,
  bool useRootNavigator = true,
  RouteSettings? routeSettings,
}) async {
  final list = <Widget>[];

  if (inApp) {
    list.add(
      CupertinoActionSheetAction(
        onPressed: () {
          if (onTap != null) onTap();
          onAppTap!();
        },
        isDefaultAction: true,
        child: Text(CoreKitS.of(context).inAppMap),
      ),
    );
  }

  if (isShowTips) {
    list
      ..add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.aMap, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).aMapTitle),
        ),
      )
      ..add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.tencent, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).tencentMapTitle),
        ),
      )
      ..add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.biadu, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).baiduMapTitle),
        ),
      );

    if (Platform.isIOS) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.apple, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).appleMapTitle),
        ),
      );
    }
  } else {
    if (await mapUtilGotoAMap(context, longitude, latitude)) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.aMap, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).aMapTitle),
        ),
      );
    }

    if (await mapUtilGotoTencentMap(context, longitude, latitude)) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.tencent, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).tencentMapTitle),
        ),
      );
    }

    if (await maputilGotoBaiduMap(context, longitude, latitude)) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.biadu, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).baiduMapTitle),
        ),
      );
    }

    if (Platform.isIOS) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () async {
            if (onTap != null &&
                await openMap(context, MapType.biadu, longitude, latitude,
                    isShowTips: isShowTips)) {
              onTap();
            }
          },
          isDefaultAction: true,
          child: Text(CoreKitS.of(context).appleMapTitle),
        ),
      );
    }
  }

  return showCupertinoModalPopup<T?>(
    context: context,
    builder: (context) {
      return CupertinoActionSheet(
        actions: list,
        cancelButton: CupertinoActionSheetAction(
          isDestructiveAction: true,
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text(CoreKitS.of(context).cancel),
        ),
      );
    },
    useRootNavigator: useRootNavigator,
    routeSettings: routeSettings,
  );
}

/// 高德地图
Future<bool> mapUtilGotoAMap(
    BuildContext context, String longitude, String latitude) async {
  final url =
      '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
  final canUrl = await canLaunchUrl(Uri.parse(url));
  if (!canUrl) {
    CoreKitLogger().e('未检测到高德地图~');
    return false;
  }

  // await launch(url);
  return canUrl;
}

/// 腾讯地图
Future<bool> mapUtilGotoTencentMap(
    BuildContext context, String longitude, String latitude) async {
  final url =
      'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';
  final canUrl = await canLaunchUrl(Uri.parse(url));
  if (!canUrl) {
    CoreKitLogger().e('未检测到腾讯地图~');
    return false;
  }
  // await launch(url);
  return canUrl;
}

/// 百度地图
Future<bool> maputilGotoBaiduMap(
    BuildContext context, String longitude, String latitude) async {
  final url =
      'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';

  final canUrl = await canLaunchUrl(Uri.parse(url));
  if (!canUrl) {
    CoreKitLogger().e('未检测到百度地图~');
    return false;
  }
  // await launch(url);
  return canUrl;
}

/// 苹果地图
Future<bool> gotoAppleMap(String longitude, String latitude,
    {bool isShowTips = false}) async {
  final url = 'https://maps.apple.com/?&daddr=$latitude,$longitude';
  final canUrl = await canLaunchUrl(Uri.parse(url));
  if (!canUrl) {
    CoreKitLogger().e('打开失败苹果地图~');
    return false;
  }
  // await launch(url);
  return canUrl;
}

/// 苹果地图
Future<bool> openMap(
    BuildContext context, MapType mapType, String longitude, String latitude,
    {bool isShowTips = false}) async {
  var url = '';
  var tips = '';
  switch (mapType) {
    case MapType.aMap:
      url =
          '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
      tips = CoreKitS.of(context).aMapError;
      break;
    case MapType.tencent:
      url =
          'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';

      tips = CoreKitS.of(context).tencentMapError;
      break;
    case MapType.biadu:
      url =
          'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';
      tips = CoreKitS.of(context).baiduMapError;
      break;
    case MapType.apple:
      url = 'https://maps.apple.com/?&daddr=$latitude,$longitude';
      break;
  }
  Navigator.pop(context);

  if (isShowTips) {
    final canUrl = await canLaunchUrl(Uri.parse(url));
    if (!canUrl) {
      if (isShowTips) {
        toastError(tips);
      }
      return false;
    }
  }
  await launchUrl(Uri.parse(url));
  return true;
}
